//常量
var conferenceConfig = {
    isVideo: false,
    vcsUrl: '',
    key: null,
    numbers: 0,
    displayNum: '',
    protocol: 'http',
    ip: '',
    port: '',
    cameraId: '',
    micId: '',
    audioId: ''
}
var icon = {
    talking: './dist/img/conference/mic_talking.gif',
    mute: './dist/img/conference/mic_mute.png',
    normal: './dist/img/conference/mic_normal.png',
    in:'./dist/img/conference/in_room.png',
    in_mute:'./dist/img/conference/in_room_mute.png'
}
var deviceList = {
    cameraList: [],
    micList: [],
    audioList: []
}
var conferenceData = {
    currentRoom: '',
    mode: 'panel',
    selectParticipant: '',
    selectName: '',
    rooms: {},
    roomMeetings: {},
    inRoom: false,
    treeData: null,
    isHy: false,
    inviteInfo:{
        content:'',
        userId:'',
        roomName:'',
        roomNum:'',
        show:false
    }
}
var videoConstraints = {
    audio:true,
    video:{
        width:{
            min:320,
            max:1280,
            ideal:1280,
        },
        height:{
            min:240,
            max:720,
            ideal:720
        },
        frameRate:{
            min:15,
            max:30
        }
    }
}
var vcs = null
var topTranslate = 0
var isFull = false

function $nsGcmWsVcsCallInit(){
	let _isHy = $('#conference').attr('hidden')
	if (_isHy == 'hidden') {
		conferenceData.isHy = false
	} else {
		conferenceData.isHy = true
	}
	let videoConf = localStorage.getItem('rh_videoConf')
	
	conferenceConfig.protocol = window.location.protocol.indexOf('https')>-1?'https':'http'
	//初始化会议接口
	// console.log('初始化会议接口!!!!!')
	conferenceApi._init(conferenceConfig.protocol, host, authForAll)

	if (videoConf && parseInt(videoConf) > 0) {
		conferenceConfig.numbers = parseInt(videoConf)
		conferenceConfig.isVideo = true
		let videoConfig = localStorage.getItem('rh_confConfig')
		if (videoConfig) {
			let _videoConfig = JSON.parse(videoConfig)
			conferenceConfig = Object.assign(conferenceConfig, _videoConfig)
			if (!conferenceConfig.displayNum) {
				conferenceConfig.displayNum = '10000'
			}
			if (conferenceConfig.ip) {
				conferenceConfig.vcsUrl = (conferenceConfig.protocol === 'https' ? 'wss' : 'ws') + '://' + conferenceConfig.ip + ':' + conferenceConfig.port + '/vcs/call'
			} else {
				conferenceConfig.vcsUrl = ''
			}

		}
	}
	//开始建立链接
	//console.log('开始建立链接 !!!!', conferenceConfig)
	var options = {appKey:conferenceConfig.key, limit: parseInt(videoConf), url: conferenceConfig.vcsUrl,
		handle: handleMessage}
	//console.log('options:', options)
	vcs = conferenceUtils.VcsSocket(options, () => {
		//console.log('connect to VCS successful!')
		conferenceConfig.isVideo = true
	})
	//console.log('vcs:', vcs)
	//console.log('sysUserId:', sysUserId)
	// conferenceApi.queryUserConfig(sysUserId).then(response=>{
	//     if (response) {
	//         conferenceConfig.micId = response.micId
	//         conferenceConfig.cameraId = response.cameraId
	//         conferenceConfig.audioId = response.speakId
	//     }
	//     //获取设备列表
	//     getDeviceList()
	// })
	//设置日志的方法
	confLog.init(websocket,username)

	window.addEventListener('resize',reloadConferenceContent)
}
function getDeviceList() {
    deviceList.audioList = []
    deviceList.cameraList = []
    deviceList.micList = []
    navigator.mediaDevices.enumerateDevices().then(devices=>{
        if (devices) {
            devices.forEach(device=>{
                let json = {id:device.deviceId,value:device.deviceId, label: device.label}
                if (device.kind === 'audiooutput') {
                    deviceList.audioList.push(json)
                    return
                }
                if (device.kind === 'videoinput') {
                    deviceList.cameraList.push(json)
                    return
                }
                if (device.kind === 'audioinput') {
                    deviceList.micList.push(json)
                }
            })
            if (conferenceConfig.cameraId) {
                let cameraIds = deviceList.cameraList.map(d=>d.id)
                if (cameraIds.indexOf(conferenceConfig.cameraId) < 0) {
                    conferenceConfig.cameraId = deviceList.cameraList.length > 0 ? deviceList.cameraList[0].value : ''
                }
            }
            if (conferenceConfig.audioId) {
                let audioIds = deviceList.audioList.map(d=>d.id)
                if (audioIds.indexOf(conferenceConfig.audioId) < 0) {
                    conferenceConfig.audioId = deviceList.audioList.length > 0 ? deviceList.audioList[0].value : ''
                }
            }
            if (conferenceConfig.micId) {
                let micIds = deviceList.micList.map(d=>d.id)
                if (micIds.indexOf(conferenceConfig.micId) < 0) {
                    conferenceConfig.micId = deviceList.micList.length > 0 ? deviceList.micList[0].value : ''
                }
            }
            saveDeviceConfig()
        }
    })
}

function saveDeviceConfig() {
    let config = {userId:sysUserId,cameraId:conferenceConfig.cameraId,micId:conferenceConfig.micId,speakId:conferenceConfig.audioId}
    conferenceApi.saveUserConfig(config)
}

//处理查询的固定会议室数据
function generatorConf(data) {
    if (data && data.length > 0) {
        data.forEach(d=>{
            if (d.isDept == 1 && d.children) {
                d.tags = [0]
                d.icon = 'glyphicon glyphicon-folder-close'
                generatorConf(d.children)
            } else {
                if (d.conf_name && !conferenceData.rooms[d.conf_name]) {
                    // 生成会议室
                    let options = {
                        name: d.conf_name,
                        no: d.confno,
                        number: d.conf_num,
                        route: d.route_group_id,
                        host: '',
                        intercom: d.support_intercom,
                        isVideo: d.isVideo == 1,
                        record: d.support_record == 1,
                        deptId: d.deptId,
                        isTemp: false,
                        confApi: conferenceApi,
                        forceRecord: d.support_record == 1
                    }
                    let room = conferenceUtils.Room(options)
                    conferenceData.rooms[d.conf_name] = room
                }
                let r = conferenceData.rooms[d.conf_name]
                conferenceData.roomMeetings[d.conf_name] = r.meetings().length
                if (r && r.isVideo) {
                    d.icon = 'glyphicon glyphicon-facetime-video'
                }else {
                    d.icon = 'glyphicon glyphicon-earphone'
                }
                d.tags = [r.meetings().length]
            }
        })
    }
}

function changeTreeNum(roomName, num) {
    let roomNums = conferenceData.roomMeetings[roomName]
    if (!roomNums) {
        if (num < 0) {
            loadConferenceLeft()
            return
        }
        conferenceData.roomMeetings[roomName] = num
    } else {
        let n = roomNums + num
        if (n < 0) {
            n = 0
        }
        conferenceData.roomMeetings[roomName] = n
    }

    loadConferenceLeft()
}

function setTreeNum(roomName, num) {
    let roomNums = conferenceData.roomMeetings[roomName]
    if (!roomNums) {
        if (num < 0) {
            loadConferenceLeft()
            return
        }
        conferenceData.roomMeetings[roomName] = num
    } else {
        if (num < 0) {
            num = 0
        }
        conferenceData.roomMeetings[roomName] = num
    }

    loadConferenceLeft()
}
//生成树
function loadConferenceLeft() {
    //处理树，修改TAGS数量
    let nums = conferenceData.roomMeetings
    if (nums && Object.keys(nums).length > 0) {
        reloadConferenceNum(conferenceData.treeData, nums)
        //向上统计数量
        reloadDeptNum(conferenceData.treeData)
    }
    //根据会议室信息生成树
    // $('#confTree').text('')
    if (conferenceData.treeData) {
        let data = JSON.parse(JSON.stringify(conferenceData.treeData).replace(/"conf_name":/g, '"text":').replace(/"deptName":/g, '"text":').replace(/"children":/g, '"nodes":'))
        // $('#confTree').css('text-align','left')
        // $('#confTree').treeview({
        //     data: data,
        //     showTags:true,
        //     onNodeSelected: function (event, node) {
        //         if (node.isDept == 0) {
        //             loadRoom(node.text)
        //         }
        //     },
        //     onNodeExpanded: function (event, node) {
        //         if (node.isDept == 1) {
        //             treeDeptChange(node.nodeId,'glyphicon-folder-open')
        //         }
        //     },
        //     onNodeCollapsed: function (event, node) {
        //         if (node.isDept == 1) {
        //             treeDeptChange(node.nodeId,'glyphicon-folder-close')
        //         }
        //     }
        // })
    }else {
        // $('#confTree').css('text-align','center')
        // $('#confTree').text('无会议室')
    }

    // $('#confTreeLs').text('')
    let lsConf = []
    for (let key in conferenceData.rooms) {
        let room = conferenceData.rooms[key]
        if (room.isTemp) {
            let json = {
                text: room.name,
                value: room.no,
                number: room.number,
                tags: conferenceData.roomMeetings[room.name] ? [conferenceData.roomMeetings[room.name]] : [0],
                isVcs: room.isVideo,
                icon: room.isVideo ? 'glyphicon glyphicon-facetime-video':'glyphicon glyphicon-earphone'
            }
            lsConf.push(json)
        }
    }
    if (lsConf.length > 0) {
        // $('#confTreeLs').css('text-align','left')
        // $('#confTreeLs').treeview({
        //     data: lsConf,
        //     showTags:true,
        //     onNodeSelected: function (event, node) {
        //         loadRoom(node.text)
        //     },
        // })
    }else {
        // $('#confTreeLs').css('text-align','center')
        // $('#confTreeLs').text('无会议室')
    }
}

//修改会议的统计数量
function reloadConferenceNum(treeData, nums) {
    if (treeData && treeData.length > 0) {
        treeData.forEach(d => {
            if (d.isDept == 0) {
                d.tags = nums[d.conf_name] ? [nums[d.conf_name]] : [0]
            } else {
                d.tags = [0]
            }
            if (d.children && d.children.length > 0) {
                reloadConferenceNum(d.children, nums)
            }
        })
    }
    return treeData
}
//修改分区的统计数量
function reloadDeptNum(treeData) {
    if (treeData) {
        treeData.forEach(t=>{
            if (t.isDept == 1) {
                let num = 0
                if (t.children && t.children.length > 0) {
                    t.children.forEach(c=>{
                        num+=c.tags[0]
                        reloadDeptNum(t.children)
                    })
                }
                t.tags = [num]
            }
        })
    }
}
//分区图标改变
function treeDeptChange(nodeId, icon) {
    $('[class$="node-confTree"][data-nodeid="' + nodeId + '"]').find('.node-icon').each(function (index, node) {
        node.classList.remove('glyphicon-folder-close')
        node.classList.remove('glyphicon-folder-open')
        node.classList.add(icon)
    })
}

//根据名称加载会议室
function loadRoom(roomName, cb) {
    if (conferenceData.currentRoom != roomName) {
        conferenceData.selectParticipant = ''
    }
    clearSrc(conferenceData.currentRoom)
    conferenceData.currentRoom = roomName
    if (conferenceData.currentRoom) {
        let room = conferenceData.rooms[conferenceData.currentRoom]
		console.log('根据名称加载会议室::', roomName)
		console.log(room, room.isVideo, room.isTemp)
        if (room) {
            //加载会议室成员
            if (room.isTemp) {
                conferenceApi.queryTempConferenceMembers(room.name).then(response=>{
                    if (response.code === 10002) {
                        delete conferenceData.rooms[room.name]
                        conferenceData.currentRoom = ''
                        return
                    }
                    if (response.code === 200) {
                        let data = response.data
                        if (data && data.length > 0) {
                            data.forEach(d=>{
                                let options = {
                                    name: d.name,
                                    roomName: room.name,
                                    number: d.exten,
                                    type: d.type,
                                    isVcs: d.vcs,
                                    isTemp: d.temp,
                                    gradeNumber: d.gradeNum,
                                    gradeName: d.gradeName,
                                    net: d.net,
                                    deptId: d.deptId,
                                    deptName: d.deptName,
                                    icon: processIcon(d.type, d.iconType),
                                    isControl:d.name == username,
                                }
                                let participant = conferenceUtils.Participant(options)
                                d.status == 'UnKnown' ? d.status = 'UnKnow' : null

                                participant.setStatus(d.status)
                                room.addParticipant(participant,d.inRoom)
                            })
                        }else {
                            delete conferenceData.rooms[room.name]
                            delete conferenceData.roomMeetings[room.name]
                            loadConferenceLeft()
                            loadRoom('')
                            return
                        }
                    }
                    userIsInRoom()
                    conferenceHtml()
					typeof cb === 'function' && cb()
                })
            }else {
                conferenceApi.queryConferenceMembers(room.no,room.name).then(response=>{
                    if (response.code === 200) {
                        let data = response.data
                        if (data && data.length > 0) {
                            data.forEach(d=>{
                                let options = {
                                    name: d.name,
                                    roomName: room.name,
                                    number: d.exten,
                                    type: d.type,
                                    isVcs: d.vcs,
                                    isTemp: d.temp,
                                    gradeNumber: d.gradeNum,
                                    gradeName: d.gradeName,
                                    net: d.net,
                                    deptId: d.deptId,
                                    deptName: d.deptName,
                                    mute: d.mute,
                                    icon: processIcon(d.type, d.iconType),
                                    isControl:d.name == username,
                                }
                                let participant = conferenceUtils.Participant(options)
                                participant.setMute(d.mute)
                                d.status == 'UnKnown' ? d.status = 'UnKnow' : null

                                participant.setStatus(d.status)
                                room.addParticipant(participant,d.inRoom)
                            })
                        }
                    }
                    userIsInRoom()
                    conferenceHtml()
					typeof cb === 'function' && cb()
                })
            }
        }
    }
}

function processIcon(type, extentType) {
    if (type == 1) {
        //return extenIcon(extentType)
        return 'glyphicon glyphicon-phone-alt'
    }else if (type == 2) {
        return 'glyphicon glyphicon-phone'
    }else if (type == 4 || type == 5) {
        return 'glyphicon glyphicon-facetime-video'
    }else if (type == 6) {
        return 'glyphicon glyphicon-user'
    } else {
        return 'glyphicon glyphicon-question-sign'
    }
}

function extenIcon(type) {
    let iconClass = 'other'
    switch (type) {
        case '1':
            iconClass = 'mobile'
            break
        case '2':
            iconClass = 'speak'
            break
        case '3':
            iconClass = 'broad'
            break
        case '4':
            iconClass = 'door'
            break
        case '5':
            iconClass = 'pc'
            break
        case '6':
            iconClass = 'car'
            break
        case '7':
            iconClass = 'voice'
            break
        case '8':
            iconClass = 'view'
            break
        case '9':
            iconClass = 'other'
            break
        default:
            iconClass = 'other'
            break
    }
    return iconClass
}

//处理成员状态
function panelClass(status) {
    var _class = 'panel col-md-1 '
    var _status = '未知'
    if (!status) {
        return ['未知','col-md-1 panel-default']
    }
    switch (status.toLowerCase()) {
        case 'idle':
            _class += ' panel-primary'
            _status = '空闲'
            break
        case 'ringing':
            _class += ' panel-danger'
            _status = '振铃'
            break
        case 'talking':
            _class += ' panel-success'
            _status = '通话'
            break
        case 'broading':
            _class += ' panel-info'
            _status = '广播'
            break
        case 'offline':
            _class += ' panel-default'
            _status = '离线'
            break
        case 'unknow':
            _class += ' panel-warning'
            _status = '未知'
            break
    }
    return [_status, _class]
}

//点击选择成员
function select(name) {
    conferenceData.selectParticipant = name
    //其余的去除选中
    $('#confrenceindex .panel').removeClass('selected')
    //设置选中的框为红色
    $('[id=\'hy_'+name+'\']').addClass('selected')
}

//设置选中
function selectMeeting(name, value, type) {
	return false;
    conferenceData.selectParticipant = value
    conferenceData.selectName = name
    $('#confrenceindex .meeting-div').removeClass('selected')
    $('[id="va-' + name+'"]').addClass('selected')
    //列表模式下切换主框画面
    if (conferenceData.mode == 'list') {
        if (type != 'main') {
            changeMain()
        }
        let mainNode = $('[id="main-va-' + name+'"]')
        if (mainNode) {
            mainNode.addClass('selected')
        }
    }
}

//分机或者成员的变化
function conferenceMemberChange(roomName, number, appKey, name, type) {
    //判断当前是否是显示的会议室模块

    if (!type || (!conferenceData.isHy && type != 'ring')) {
        return
    }
    let room = null
    if (roomName) {
        room = getRoom(roomName)
        //处理数量
        if (type == 'enter' || type == 'leave') {
            if (room) {
                changeTreeNum(room.name, type == 'enter' ? 1 : -1)
            }
        }
        if (room && room.name != conferenceData.currentRoom) {
            return
        }
    }else{
        room = conferenceData.rooms[conferenceData.currentRoom]
    }
    if (room) {
        if (type == 'hangup' && room.name == conferenceData.currentRoom) {
            //去除分机
            room.removeParticipant('number', number, appKey)
            loadRoom(room.name)
        }
        if (room.isVideo && room.isMeeting) {
            return
        }
    }
    try {
        switch (type.toLowerCase()) {
            case 'ring':
                if (!roomName) {
                    return
                }
                if (!room) {
                    room = newTempRoom(roomName)
                    conferenceData.rooms[roomName] = room
                }
                if (room.name == conferenceData.currentRoom && conferenceData.isHy) {
                    if (!room.isVideo && !conferenceData.inRoom) {
                        loadRoom(room.name)
                    }
                }
                break
            case 'talk':
                if (room) {
                    //判断是否在当前会议室中
                    room._inRoom(number, appKey).then(result => {
                        if (result.data) {
                            loadRoom(room.name)
                            //changeTreeNum(room.name, 1)
                        }
                    }).catch(error=>{
                        console.error(error)
                    })
                }

                break
            case 'idle':
                if (room) {
                    room._inRoom(number, appKey).then(result => {
                        if (result.data) {
                            loadRoom(room.name)
                        }
                    }).catch(error=>{
                        console.error(error)
                    })
                }

                break
            case 'broad':
                if (room) {
                    room._inRoom(number, appKey).then(result => {
                        if (result.data) {
                            loadRoom(room.name)
                        }
                    }).catch(error=>{
                        console.error(error)
                    })
                }

                break
            case 'offline':
                if (room) {
                    room._inRoom(number, appKey).then(result => {
                        if (result.data) {
                            loadRoom(room.name)
                        }
                    }).catch(error=>{
                        console.error(error)
                    })
                }

                break
            case 'hangup':
                let _rooms = conferenceData.rooms
                if (_rooms) {
                    for (const key in _rooms) {
                        let _room = _rooms[key]
                        _room.changeInvite('number', appKey, number).then(result=>{

                            if (result.data) {
                                if (result.room.name == conferenceData.currentRoom) {
                                    joinInfo()
                                }
                            }
                        }).catch(error=>{
                            console.error(error)
                        })
                    }
                }
                if (room) {
                    room._inRoom(number, appKey).then(result => {
                        if (result) {
                            if (number == conferenceData.selectParticipant) {
                                conferenceData.inRoom = false
                            }
                            loadRoom(room.name)
                        }
                    }).catch(error=>{
                        console.error(error)
                    })
                }
                break
            case 'enter':
                if (room) {
                    room.removeInviteParticipant('number',number,appKey)
                    room.asyncInfo(name,'enter')
                    if (room.name == conferenceData.currentRoom) {
                        loadRoom(room.name)
                    }
                }else{
                    room = newTempRoom(roomName)
                    conferenceData.rooms[roomName] = room
                }
                break
            case 'leave':
                if (room) {
                    room.removeParticipant('number', number, appKey)
                    room.asyncInfo(name,'leave')
                    if (room.name == conferenceData.currentRoom) {
                        loadRoom(room.name)
                    }
                }
                break
            case 'mute':
                if (room) {
                    room.info('number', number, appKey, 'mute')
                    let mute = room.getParticipantByNumber(number, appKey)
                    mute ? mute.setMute(true) : null
                    if (room.name == conferenceData.currentRoom) {
                        loadRoom(room.name)
                    }
                }
                break
            case 'unmute':
                if (room) {
                    room.info('number', number, appKey, 'unMute')
                    let unMute = room.getParticipantByNumber(number, appKey)
                    unMute ? unMute.setMute(false) : null
                    if (room.name == conferenceData.currentRoom) {
                        loadRoom(room.name)
                    }
                }
                break
        }
    }catch (e) {
        console.error(e)
    }
}

//判断是否在会议室里
function userIsInRoom() {
    //重置
    conferenceData.inRoom = false
    let room = conferenceData.rooms[conferenceData.currentRoom]
    if (!room || !room.getParticipants()) {
        console.log('user is in room param is error!', room)
        return
    }
    if (!room.isMeeting) {
        conferenceData.inRoom = false
        return
    }
    let participants = room.meetings('Talking')
    let camera = false
    for (let i = 0; i < participants.length; i++) {
        let participant = participants[i]
        if (room.isVideo) {
            if (participant.type == 6 && participant.name == username) {
                conferenceData.inRoom = true
                camera = participant.muteVideo
            }
        }else {
            if (participant.type == 1 && (participant.number == callee || participant.number == caller)) {
                conferenceData.inRoom = true
                camera = false
            }
        }
    }
}
//根据会议室成员
function conferenceHtml() {
    let room = conferenceData.rooms[conferenceData.currentRoom]
    if (!room) {
        return
    }
    let participants = room.getParticipants()
    let meetings = room.meeting
    if (participants.length <= 0) {
        return
    }
    //1.中间主体部分

    if (room.isMeeting && conferenceData.inRoom) {
        //开会中
        if (conferenceData.mode == 'list') {
            listContent()
        }else {
            openRoomContent()
        }
    }else {
        var _html = ''
        //未开会
        participants.forEach(participant=>{
            let panel = panelClass(participant.status)
            let deptName = participant.deptName
            deptName == 'all_area' ? deptName = '全部分区' : (deptName == 'only_admin' ? deptName = '仅管理员可见' : null)
            let name = participant.type == 1 ? participant.number : participant.name
            let number = participant.number
            participant.type == 6 ? number = participant.name : ((participant.type == 4 || participant.type == 5) ? number = participant.net : '')
            let show = meetings.indexOf(participant.name) > -1
            let _icon = icon.in
            if (number == null) {
                number = ''
            }
            participant.muted ? _icon = icon.in_mute : null
            let content = '<div class="' + panel[1] + '" id="hy_' + name + '" onclick="select(\''+name+'\')">' +
                '<div class="panel-heading"><h6 class="panel-title font-weight-normal" id="ht_' + name + '"><img src="'+_icon+'" style="display: '+(show ? "inline-block":"none")+'" class="in-room-icon"/>' + panel[0] + '</h6></div>' +
                '<div class="panel-body"><ul class="list-unstyled"><li>' + deptName + '</li><li><i id="hi_' + name + '" class="' + participant.icon + '"></i>' + name + '</li><li>' + number + '</li></ul></div>' +
                '</div>'
            _html+=content
        })

        $('#confrenceindex').html(_html)
        conferenceData.mode = 'panel'
        $('.panel').addClass('col-md-1')
    }
    joinInfo()
    operationInfo()
}
//加载会议室时生成
function openRoomContent() {
	console.log('openRoomContent::')
    let room = conferenceData.rooms[conferenceData.currentRoom]
    if (!room || !conferenceData.inRoom || !room.isMeeting) {
        return
    }
    let participants = room.getParticipants()
    let meetings = room.meeting
    let _participants = participants.filter(p => meetings.indexOf(p.name) > -1)
    if (_participants.length <= 0) {
        return
    }
    let _html = ''
    _participants.forEach(participant=>{
        let _img = ''
        participant.muted ? _img = icon.mute : _img = icon.normal
        let showVideo = (participant.isVcs && !participant.muteVideo)
        let select = participant.type == 1 ? participant.number : participant.name
        let content = '<div id="va-'+participant.name+'" class="meeting-div h5videowrapper h5container" onclick="selectMeeting(\''+participant.name+'\',\''+select+'\')" ondblclick="changeMode(\''+participant.name+'\',\''+select+'\')">' +
            '<div id="v-' + participant.name + '" style="display: '+(showVideo ? "block":"none")+'" class="meeting-content-div">' +
            '<video id="video-' + participant.name + '" class="video-js vjs-default-skin h5video" webkit-playsinline playsinline autoplay></video>' +
            '<audio id="audio-' + participant.name + '" style="display: none" class="video-js vjs-default-skin h5video" webkit-playsinline playsinline autoplay></audio>' +
            '<div id="vn-' + participant.name + '" class="videoname">' +
            '<img src="' + _img + '" id="img-'+participant.name+'"/>' + participant.name + ' ' +
            '</div>' +
            '</div>' +
            '<div id="a-'+participant.name+'" class="meeting-content-div" style="display: '+(showVideo ? "none":"flex")+'">' +
            '<div class="name-div">' +
            '<div>' +
            '<span title="'+participant.name+'">'+participant.name+'</span>' +
            '</div>' +
            '</div>' +
            '<div id="an-' + participant.name + '" class="videoname">' +
            '<img src="' + _img + '" id="img-'+participant.name+'"/>' + participant.name + ' ' +
            '</div>' +
            '</div>' +
            '</div>'
        _html+=content
    })
    $('#confrenceindex').html(_html)
    setVideoSize(isFull)
    //设置选中
    if (conferenceData.selectParticipant) {
        selectMeeting(conferenceData.selectName, conferenceData.selectParticipant)
    }
    if (room.isVideo) {
        //给每个视频窗赋值
        _participants.forEach(participant=>{
            if (participant.rtcPeer) {
                let node = participant.getElement()
                node.srcObject = participant.name==username ? participant.rtcPeer.getLocalStream() : participant.rtcPeer.getRemoteStream()
                if (participant.name == username) {
                    node.muted = true
                }
                node.addEventListener('pause',()=>{
                    node.play()
                })
            }
        })
    }
}

function setVideoSize(full) {
    let room = conferenceData.rooms[conferenceData.currentRoom]
    if (!room) {
        return
    }
    let _participants = room.meetings('Talking')
    //设置每一个视频框的高度
    let allHeight = $('#conference').height() - 50
    let allWidth = $('#conference').width() - 15
    if (full) {
        allHeight = document.body.clientHeight - 15
        allWidth = document.body.clientWidth - 15
    }
    let row=1,col=1
    let allNum = _participants.length
    if (allNum > 1 && allNum < 3) {
        row = 1
        col = 2
    }
    if (allNum > 2 && allNum < 5) {
        row = 2
        col = 2
    }
    if (allNum > 4 && allNum < 7) {
        row = 2
        col = 3
    }
    if (allNum > 6 && allNum < 10) {
        row = 3
        col = 3
    }

    if (allHeight) {
        if (_participants.length > 1) {
            if (full) {
                if (allNum > 9) {
                    conferenceData.mode = 'list'
                    listContent()
                    return
                }
                $('.meeting-div').css({'height': allHeight / row})
                let precent = 100 / col + '%'
                $('.meeting-div').css({'width': 'calc('+precent+' - 5px)'})
                return
            }
            $('.meeting-div').css({'height': allHeight / 2})
            $('.meeting-div').css({'width': 'calc(50% - 5px)'})
        }else {
            $('.meeting-div').css({'height': allHeight})
            $('.meeting-div').css({'width': allWidth})
        }

    }
}

function reloadConferenceContent(full) {
    if (!conferenceData.isHy) {
        return
    }
    let room = conferenceData.rooms[conferenceData.currentRoom]
    if (!room || !room.isMeeting || !conferenceData.inRoom) {
        return
    }
    isFull = full
    if (conferenceData.mode == 'panel') {
        setVideoSize(full)
    } else {
        let allHeight = $('#conference').height() - 50
        if (full) {
            allHeight = document.body.clientHeight
        }
        $('.list-content').css({'height': allHeight})
    }
}

function firstEnterConference(){
    //判断是否是第一次进入会议室
    let nodes = $('.meeting-div')
    if (!nodes || nodes.length <= 0) {
        $('#confrenceindex').html('')
        //默认为卡片模式
        conferenceData.mode = 'panel'
        //显示加入按钮
        $('.btn-hy button[name="join"]').attr('style','display:inline-block')
        $('.btn-hy button[name="leave"]').attr('style','display:none')
        $('.btn-hy button[name="opencamera"]').attr('style','display:none')
        $('.btn-hy button[name="closecamera"]').attr('style','display:none')
    }
}

function onClickGcmItem(name, select, participant){
	const pt = JSON.parse(participant)
	const id = `gcm-itempane-${name}`
	const hasCls = $('#gcmPane').find(`#${id}`).hasClass('big');
	$('#gcmPane').find('.vm-item-wrap').removeClass('big');
	if(hasCls){
		$('#gcmPane').find(`#${id}`).removeClass('big');
	}else{
		$('#gcmPane').find(`#${id}`).addClass('big');
	}
	setTimeout(() => {
		NS_CONFIG.EVENT_BUS.$emit('nsCallGcmItemPane',{ name, select, pt})
	}, 20)
}

//插入节点
function insertNode(participant){
	console.log('gcm insertNode insertNode', participant, $('#gcmPane'))
	if(!$('#gcmPane').length){
		uni.showToast({
			title: '????gcmpane'
		})
		return false
	}
    firstEnterConference()
    //先判断是否存在节点
    let node = $('[id="va-' + participant.name+'"]')
    if (!node || node.length <=0) {
        let _img = ''
        participant.muted ? _img = icon.mute : _img = icon.normal
        let showVideo = (participant.isVcs && !participant.muteVideo)
        let select = participant.type == 1 ? participant.number : participant.name
		let vid = `va-${participant.name}`;
		let itemPaneId = `gcm-itempane-${participant.name}`;
        const content = `
			<div class="vm-item" data-user="${participant.name}">
				<div class="vm-item-bottom">
					<div class="vm-switch-icon" onclick="onClickGcmItem('${participant.name}', '${select}', '${JSON.stringify(participant)}')">
						<div class="iconfont2 ve-icon-full"></div>
						<div class="iconfont2 ve-icon-unfull"></div>
					</div>
				</div>
				<div id="va-${participant.name}" class="meeting-div h5videowrapper h5container" ondblclick="changeMode('${participant.name}', '${select}')">
					<div id="v-${participant.name}" style="display: ${showVideo ? 'block' : 'none'}" class="meeting-content-div">
						<video id="video-${participant.name}" class="video-js vjs-default-skin h5video" webkit-playsinline playsinline autoplay></video>
						<audio id="audio-${participant.name}" style="display: none" class="video-js vjs-default-skin h5video" webkit-playsinline playsinline autoplay>
						</audio>
					</div>
				</div>
			</div>
        `;
		console.log('conferenceData.mode::', conferenceData.mode, content);
		$('#gcmPane').prepend($(`<div class="vm-item-wrap" id="${itemPaneId}">${content}</div>`))
    }
    let _node = participant.getElement()
	console.log(`$('#gcmPane')::`, $('#gcmPane'), `_node::`, _node)
    console.log('participant::', participant, username)
    //新建立通信
    if (participant.isVcs && !participant.rtcPeer) {
        let _constrains = $.extend({},videoConstraints)
        let options = {}
        if (participant.name == username) {
            _constrains.video.deviceId = conferenceConfig.cameraId
            _constrains.audio = {deviceId: conferenceConfig.micId}
            options = {
                localVideo: _node,
                mediaConstraints: _constrains,
                onicecandidate: participant.onIceCandidate.bind(participant)
            }
            participant.rtcPeer = kurentoUtils.WebRtcPeer.WebRtcPeerSendonly(options,function (error) {
                if (error) {
                    return console.error(error)
                }
                console.log('this11111:::', this)
                this.generateOffer(participant.offerToReceiveVideo.bind(participant))
            })
            console.log('11111participant.rtcPeer::', participant.rtcPeer)
        } else {
            options = {
                remoteVideo: _node,
                onicecandidate: participant.onIceCandidate.bind(participant)
            }
            participant.rtcPeer = kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(options, function (error) {
                if (error) {
                    return console.error(error)
                }
                console.log('this2222:::', this)
                this.generateOffer(participant.offerToReceiveVideo.bind(participant))
            })
            console.log('22222participant.rtcPeer::', participant.rtcPeer)
        }
        //建立声音监听
        participant.rtcPeer.peerConnection.onconnectionstatechange = (rtc, event) => {
            if (rtc.target.connectionState === 'connected' && !participant.speakHark) {
                let stream = participant.name == username ? participant.rtcPeer.getLocalStream() : participant.rtcPeer.getRemoteStream()
                participant.speakHark = kurentoUtils.WebRtcPeer.hark(stream,{threshold: -50})
                participant.speakHark.on('speaking',()=>{
                    let _imgNode = document.getElementById('img-'+participant.name)
                    _imgNode ? _imgNode.src = icon.talking : null
                    //是否存在main
                    let _mainNode = document.getElementById('main-img-'+participant.name)
                    _mainNode ? _mainNode.src = icon.talking : null
                    participant.speaking = true
                })
                participant.speakHark.on('stopped_speaking',()=>{
                    let _imgNode = document.getElementById('img-'+participant.name)
                    _imgNode ? _imgNode.src = icon.normal : null
                    let _mainNode = document.getElementById('main-img-'+participant.name)
                    _mainNode ? _mainNode.src = icon.normal : null
                    participant.speaking = false
                })
            }
        }
    } else {
        if (participant.rtcPeer) {
            _node.srcObject = participant.name == username ? participant.rtcPeer.getLocalStream() : participant.rtcPeer.getRemoteStream()
        }
    }
	if(_node){
		_node.addEventListener('pause',()=>{
			_node.play()
		})
	}

    if (participant.name == username) {
        conferenceData.inRoom = true
    }
    joinInfo()
    operationInfo()
}
//删除节点
function removeNode(participant) {
    //查询是否在
    let node = $('[id="va-' + participant.name+'"]').closest('.vm-item-wrap');
    if (node) {
        //删除
        node.remove()
    }
    //判断会议是否结束
    let room = conferenceData.rooms[participant.roomName]
    let reloadTree = true
    if (!room) {
        return
    }
    if (room.meetings().length <= 0) {
        room.dispose()
        if (room.isTemp) {
            delete conferenceData.rooms[room.name]
            delete conferenceData.roomMeetings[room.name]
            reloadTree = false
            conferenceData.currentRoom = ''
            loadConferenceLeft()
        }
        loadRoom(room.isTemp ? '' : room.name)
    }
    if (participant.name == username) {
        conferenceData.inRoom = false
        loadRoom(room.name)
    }
    /*if (reloadTree) {
        changeTreeNum(room.name, -1)
    }*/
    joinInfo()
    operationInfo()
}
//修改节点
function changeNode(participant) {
    if (participant.muteVideo) {
        $('[id="v-'+participant.name+'"]').attr('style','display:none')
        $('[id="a-'+participant.name+'"]').attr('style','display:flex')

        let mainVNode = $('#main-v-'+participant.name)
        if (mainVNode) {
            $('[id="main-v-'+participant.name+'"]').attr('style','display:none')
            $('[id="main-a-'+participant.name+'"]').attr('style','display:flex')
        }
    }
    if (!participant.muteVideo){
        $('[id="v-'+participant.name+'"]').attr('style','display:block')
        $('[id="a-'+participant.name+'"]').attr('style','display:none')

        let mainVNode = $('#main-v-'+participant.name)
        if (mainVNode) {
            $('[id="main-v-'+participant.name+'"]').attr('style','display:block')
            $('[id="main-a-'+participant.name+'"]').attr('style','display:none')
        }
    }
    if (participant.muted) {
        document.getElementById('img-'+participant.name).src = icon.mute
        let node = document.getElementById('main-img-'+participant.name)
        if (node) {
            node.src = icon.mute
        }
    }
    if (!participant.muted){
        document.getElementById('img-'+participant.name).src = icon.normal
        let node = document.getElementById('main-img-'+participant.name)
        if (node) {
            node.src = icon.normal
        }
    }
    joinInfo()
}
//加入、未加入
function joinInfo() {
    if (!conferenceData.currentRoom) {
        return
    }
    let room = conferenceData.rooms[conferenceData.currentRoom]
    if (!room) {
        return
    }
    $('#nav-conf-in').html('')
    $('#nav-conf-out').html('')
    //2.右侧信息部分
    //2.1开会中
    let meetings = room.meetings('Talking')
    if (meetings && meetings.length > 0) {
        let _meetingHtml = ''
        _meetingHtml+='<ul class="list-unstyled">'
        meetings.forEach(meeting=>{
            let muteIcon = meeting.muted ? 'glyphicon glyphicon-volume-off' : 'glyphicon glyphicon-volume-up'
            let videoIcon = meeting.muteVideo ? 'glyphicon glyphicon-eye-close' : 'glyphicon glyphicon-eye-open'
            let videoClickClass = meeting.name == username ? ' clickIcon' : ' clickDisabled'
            let _param = meeting.type == 1 ? meeting.number : meeting.name
            let content = '<li><span title="' + meeting.name + '"><i class="' + processIcon(meeting.type) + '"></i>' + meeting.name + '</span>' +
                '<span><i class="' + muteIcon + ' clickIcon" onclick="rightBtn(\'changeMute\',\'' + _param + '\')"></i>' +
                '<i class="' + videoIcon + videoClickClass + '" style="display: ' + (room.isVideo ? 'inline-block' : 'none') + '" onclick="rightBtn(\'changeMuteVideo\',\'' + _param + '\')"></i></span></li>'
            _meetingHtml+=content
        })
        _meetingHtml +='</ul>'
        $('#nav-conf-in').html(_meetingHtml)
    }

    //2.2未加入
    let notJoin = room.invite
    if (notJoin && notJoin.length > 0) {
        let _notJoinHtml = ''
        _notJoinHtml += '<ul class="list-unstyled">'
        notJoin.forEach(nj=>{
            let _param = nj.type == 1 ? nj.number : nj.name
            let content = '<li><span><i class="'+processIcon(nj.type)+'"></i>'+nj.name+'</span>' +
                '<span style="display: '+(nj.canInvite?"inline-block":"none")+'"><i class="glyphicon glyphicon-repeat clickIcon" onclick="rightBtn(\'reInvite\',\'' + _param + '\')"></i></span></li>'
            _notJoinHtml+=content
        })
        _notJoinHtml += '</ul>'
        $('#nav-conf-out').html(_notJoinHtml)
    }
}
//操作信息
function operationInfo() {
    if (!conferenceData.currentRoom) {
        return
    }
    let room = conferenceData.rooms[conferenceData.currentRoom]
    if (!room) {
        return
    }
    $('#conf-info').html('')
    //2.3会议信息
    let infos = room.meetingInfos
    if (infos && infos.length > 0) {
        let _infoHtml = ''
        _infoHtml += '<ul class="list-unstyled">'
        infos.forEach(info => {
            let action = operationActionName(info.type)
            if (!action) {
                return
            }
            let _info = info.name + action + info.room
            let content = '<li><span title="'+_info+'">' + info.time+'&nbsp;'+ _info + '</span></li>'
            _infoHtml+=content
        })
        _infoHtml+='</ul>'
        $('#conf-info').html(_infoHtml)
    }
}

function operationActionName(type) {
    if (!type) {
        return ''
    }
    switch (type.toLowerCase()) {
        case 'enter':
            return '进入'
        case 'leave':
            return '离开'
        case 'mute':
            return '静音'
        case 'unmute':
            return '取消静音'
        case 'startrecord':
            return '开始录像'
        case 'stoprecord':
            return '停止录像'
    }
}
//右侧按键
function rightBtn(type, value) {
    if (!type || !value) {
        return
    }
    let room = conferenceData.rooms[conferenceData.currentRoom]
    if (!room || !room.isMeeting) {
        return
    }
    let participant = room.getParticipant(value)
    if (!participant) {
        return
    }
    let temp = conferenceData.selectParticipant
    conferenceData.selectParticipant = value
    switch (type.toLowerCase()) {
        case 'changemute':
            if (participant.muted) {
                doAction('unMute')
            }else {
                doAction('mute')
            }
            break
        case 'changemutevideo':
            if (!room.isVideo || participant.name!=username) {
                break
            }
            if (participant.muteVideo) {
                doAction('opencamera')
            }else{
                doAction('closecamera')
            }
            break
        case 'reinvite':
            let msg = null
            if (!room.isVideo) {
                method = 'joinconference'
                exten = participant.number
                msg = '\'confname\':\'' + room.no + '\',\'confno\':\'' + room.no + '\',\'displaynum\':\'' + (room.isTemp ? conferenceConfig.displayNum : room.number) + '\',\'isrecord\':\'' + (room.record ? '1' : '0') + '\''
                if (participant.gradeNumber) {
                    msg = msg + ',\'appKey\':\'' + participant.gradeNumber+ '\''
                }
                send(msg)
                break
            }
            let _name = ''
            if (participant.type == 1) {
                method = 'vconf_invite'
                msg = '\'confname\':\'' + room.name + '\',\'displaynum\':\'' + (room.isTemp ? conferenceConfig.displayNum : room.number) + '\',\'confnum\':\'' + room.number + '\',\'confno\':\'' + room.no
                    + '\',\'extens\':\'' + participant.number + '\',\'record_switch\':\'' + (room.record ? '1' : '0') + '\',\'deptId\':\'' + deptId + '\',\'isInvite\':\'0\''
                exten = participant.number
                _name = participant.number
                send(msg)
            }else if (participant.type == 6) {
                if (participant.name == username) {
                    doAction('join')
                } else {
                    method = 'vconf_invite_user'
                    msg = '\'confname\':\'' + room.name + '\',\'confno\':\'' + room.no
                        + '\',\'users\':\'' + participant.name + '\''
                    send(msg)
                }
                _name = participant.name
            }else{
                inviteCamera(room.name, room.number, participant.realName || participant.name)
                _name = participant.realName
            }
            confLog.vconfJoin(room.name, _name)
            break
        default:
            console.log('type :%s not support!', type)
            break
    }
    conferenceData.selectParticipant = temp
}
//功能按钮
function confFull() {
    let elem = document.getElementById('confrenceindex')
    if (
        document.fullscreenEnabled ||
        document.webkitFullscreenEnabled ||
        document.mozFullScreenEnabled ||
        document.msFullscreenEnabled
    ) {
        if (
            document.fullscreenElement ||
            document.webkitFullscreenElement ||
            document.mozFullScreenElement ||
            document.msFullscreenElement
        ) {
            if (document.exitFullscreen) {
                document.exitFullscreen()
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen()
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen()
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen()
            }
            //this.updateUIExitFullScreen()
        } else {
            if (elem.requestFullscreen) {
                elem.requestFullscreen()
            } else if (elem.webkitRequestFullscreen) {
                elem.webkitRequestFullscreen()
            } else if (elem.mozRequestFullScreen) {
                elem.mozRequestFullScreen()
            } else if (elem.msRequestFullscreen) {
                elem.msRequestFullscreen()
            }
        }
    } else {
        console.log('Fullscreen is not supported on your browser.')
    }

}

function confSetting() {
    //设置摄像头、麦克风、扬声器
    if (deviceList.cameraList.length > 0) {
        let html = ''
        for (let i = 0; i < deviceList.cameraList.length; i++) {
            let _c = deviceList.cameraList[i]
            html += '<option value="'+_c.value+'">'+_c.label+'</option>'
        }
        $('#cameraSelect').html(html)
        set_select_checked('cameraSelect',conferenceConfig.cameraId)
    }
    if (deviceList.micList.length > 0) {
        let html = ''
        for (let i = 0; i < deviceList.micList.length; i++) {
            let _c = deviceList.micList[i]
            html += '<option value="'+_c.value+'">'+_c.label+'</option>'
        }
        $('#micSelect').html(html)
        set_select_checked('micSelect',conferenceConfig.micId)
    }
    if (deviceList.audioList.length > 0) {
        let html = ''
        for (let i = 0; i < deviceList.audioList.length; i++) {
            let _c = deviceList.audioList[i]
            html += '<option value="'+_c.value+'">'+_c.label+'</option>'
        }
        $('#audioSelect').html(html)
        set_select_checked('audioSelect',conferenceConfig.audioId)
    }
    $('#confSetting').modal('show')
}

function confInvite() {
    if (!conferenceData.currentRoom) {
        return
    }
    let room = conferenceData.rooms[conferenceData.currentRoom]
    if (!room) {
        return
    }
    addExtentAjax(room.isVideo)
    $('#hyModal').modal('show')
}

function getInviteData(json, data) {
    if (!json) {
        json = {exten:[],camera:[],user:[],link:[]}
    }
    for (let i = 0; i < data.length; i++) {
        let d = data[i]
        let param = {}
        if (d.hasOwnProperty('isDept')) {
            if (d.isDept == 0) {
                if (d.hasOwnProperty('isCamera')) {
                    param.value = d.label
                    param.name = d.cameraIP
                    param.protocol = d.protocolType
                    param.id = d.cameraId
                    json.camera.push(param)
                }else{
                    if (d.hasOwnProperty('isLinkMan')) {
                        if (d.isLinkMan == 1) {
                            param.value = d.value
                            param.name = d.label.split(',')[0]
                            param.id = d.realId
                            json.link.push(param)
                        }
                    }else {
                        param.value = d.id
                        param.label = d.employeeName
                        param.id = d.id
                        param.key = d.key
                        json.exten.push(param)
                    }

                }
            }
        }else {
            if (d.hasOwnProperty('userId')) {
                param.value = d.userId
                param.name = d.userName
                param.id = d.realId
                json.user.push(param)
            }
        }
        if (d.children && d.children.length > 0) {
            getInviteData(json,d.children)
        }
    }
    return json
}

//根据消息更新树的数量
function generatorConference(data, isVcs) {
    //更新树的数量
    if (data && data.length > 0) {
        if (isVcs) {
            //获取会议室名称，判断是否是固定会议室
            data.forEach(d => {
                let room = conferenceData.rooms[d.roomName]
                if (!room) {
                    let options = {
                        name: d.roomName,
                        no: d.roomName,
                        number: d.roomNo,
                        route: '',
                        host: '',
                        intercom: '',
                        isVideo: true,
                        record: d.record,
                        deptId: '',
                        isTemp: true,
                        confApi: conferenceApi,
                        forceRecord: d.record
                    }
                    room = conferenceUtils.Room(options)
                }
                room.addVcsParticipant(d)
                room.isMeeting = true
                conferenceData.rooms[d.roomName] = room
                conferenceData.roomMeetings[d.roomName] = d.participantNames ? d.participantNames.length : 0
            })
			console.log('pleeeeeeeeeeeeeeeeeeeeeeeeee', conferenceData.rooms)
        }else {
            //获取会议室名称，判断是否是固定会议室
            let pattern = /^\d+$/
            let confNums = new Map()
            data.forEach(d => {
                let confName = d.confname
                if (!pattern.test(confName)) {
                    let room = conferenceData.rooms[d.confname]
                    if (!room) {
                        //新建会议室
                        room = newTempRoom(confName)
                        conferenceData.rooms[confName] = room
                    }
                    room.isMeeting = true
                    //设置会议室成员数量
                    let nowNum = confNums.get(confName)
                    if (!nowNum) {
                        confNums.set(confName,1)
                    }else {
                        nowNum += 1
                        confNums.set(confName, nowNum)
                    }
                }

            })
            //设置成员数量
            for (const key in confNums) {
                if (conferenceData.rooms.hasOwnProperty(key)) {
                    conferenceData.roomMeetings[key] = confNums[key]
                }else {
                    let room = getRoom(key, 'no')
                    if (room) {
                        conferenceData.roomMeetings[room.name] = confNums[key]
                    }
                }
            }
        }
        // loadConferenceLeft()
    }
}

function newTempRoom(confName) {
    let options = {
        name: confName,
        no: confName,
        number: conferenceConfig.displayNum,
        route: '',
        host: '',
        intercom: '',
        isVideo: confName.indexOf('vcs')>-1,
        record: false,
        deptId: '',
        isTemp: true,
        confApi: conferenceApi,
        forceRecord: false
    }
    return conferenceUtils.Room(options)
}

function getRoom(value, type) {
    if (type == 'name') {
        return conferenceData.rooms[value]
    }else if (type == 'no') {
        let rooms = conferenceData.rooms
        for (const key in rooms) {
            let room = conferenceData.rooms[key]
            if (room.no == value) {
                return room
            }
        }
        return null
    }else {
        let room = conferenceData.rooms[value]
        if (!room) {
            let rooms = conferenceData.rooms
            for (const key in rooms) {
                let room = conferenceData.rooms[key]
                if (room.no == value) {
                    return room
                }
            }
            return null
        }
        return room
    }
}

function userInOuterRoom() {
    let rooms = conferenceData.rooms
    for (const key in rooms) {
        let room = rooms[key]
        if (room.name !== conferenceData.currentRoom) {
            if (room.inRoom(username)) {
                return true
            }
        }
    }
    return false
}

//开始录像
function startRecord() {
    let room = conferenceData.rooms[conferenceData.currentRoom]
    if (room.isVideo) {
        confLog.vconfStartRecord(room.name)
        vcs.startRecord(room.name, room.number)
    }
}

//停止录像
function stopRecord() {
    let room = conferenceData.rooms[conferenceData.currentRoom]
    if (room.isVideo){
        confLog.vconfStopRecord(room.name)
        vcs.stopRecord(room.name, room.number)
    }
}

function doAction(event, cb) {
    let name = ''
    if (typeof event === 'string') {
        name = event
    }else {
        if (event.target.name) {
            name = event.target.name
        }else{
            name = event.target.parentNode ? event.target.parentNode.name : ''
        }
    }
    if (!name) {
        return
    }
    let room = conferenceData.rooms[conferenceData.currentRoom]
    console.log('==doAction==', name, typeof event === 'string')
    if (name != 'full' && name != 'setting' && name != 'invite' && name != 'open' && name != 'join') {
        if (!room.isMeeting) {
			console.log('!room.isMeeting 会议未开始')
			NS_CONFIG.EVENT_BUS.$emit('nsCallNoStart')
			typeof cb === 'function' && cb()
            return console.log('meeting : %s not start!', room.name)
        }
    }
    let msg = ''
    let participant = null
    switch (name.toLowerCase()) {
        case 'full':
            confFull()
            break
        case 'setting':
            confSetting()
            break
        case 'invite':
            confInvite()
            break
        case 'kick':
            if (!conferenceData.selectParticipant) {

				uni.showToast({
					title: '请选择会议成员',
					icon: 'none'
				})
                return console.log('请选择会议成员！')
            }
            if (room.isVideo) {
                confLog.vconfLeave(room.name, conferenceData.selectParticipant)
                vcs.kick(room.name,room.number,conferenceData.selectParticipant)
            }else {
                method = 'conferencekick'
                msg = '\'confname\':\''+room.no+'\',\'confno\':\''+room.no+'\''
                participant = room.getParticipant(conferenceData.selectParticipant)
                exten = participant.number
                if (participant && participant.gradeNumber) {
                    msg += ',\'appKey\':\''+participant.gradeNumber+'\''
                }
                send(msg)
            }
            break
        case 'join':
            console.log('joinjoinjoinjoinjoinjoin', room, conferenceData);
            if (room.isVideo && !conferenceData.inRoom) {
                if (userInOuterRoom()) {
					uni.showToast({
						title: '已在其余会议室中',
						icon: 'none'
					})
                    return false;
                }
                room.changeVcsParticipant({name: username, type: 'pc', mute: false}).then(response=>{
                    confLog.vconfJoin(room.name, username)
                    vcs.joinConference(room.name, room.number, username, 'pc', '')
                })
            }
            break
        case 'leave':
            if (room.isVideo) {
                confLog.vconfLeave(room.name, username)
                vcs.leaveRoom()
            }
            break
        case 'mute':
            if (!conferenceData.selectParticipant) {
				uni.showToast({
					title: '请选择会议成员',
					icon: 'none'
				})
                return console.log('请选择会议成员！')
            }
            if (room.isVideo) {
                confLog.vconfMute(room.name, conferenceData.selectParticipant)
                vcs.mute(room.name, room.number, conferenceData.selectParticipant)
            }else {
                method = 'conferencemute'
                msg = '\'confname\':\''+room.no+'\',\'confno\':\''+room.no+'\''
                participant = room.getParticipant(conferenceData.selectParticipant)
                exten = participant.number
                if (participant && participant.gradeNumber) {
                    msg += ',\'appKey\':\''+participant.gradeNumber+'\''
                }
                send(msg)
            }
            break
        case 'unmute':
            if (!conferenceData.selectParticipant) {
				
					uni.showToast({
						title: '请选择会议成员',
						icon: 'none'
					})
                return console.log('请选择会议成员！')
            }
            if (room.isVideo) {
                confLog.vconfUnmute(room.name, conferenceData.selectParticipant)
                vcs.unMute(room.name, room.number, conferenceData.selectParticipant)
            }else {
                method = 'conferencecancemute'
                msg = '\'confname\':\''+room.no+'\',\'confno\':\''+room.no+'\''
                participant = room.getParticipant(conferenceData.selectParticipant)
                exten = participant.number
                if (participant && participant.gradeNumber) {
                    msg += ',\'appKey\':\''+participant.gradeNumber+'\''
                }
                send(msg)
            }
            break
        case 'allmute':
            if (room.isVideo) {
                confLog.vconfMuteAll(room.name)
                vcs.muteAll(room.name, room.number)
            }else {
                method = 'conferencemuteall'
                msg = '\'confname\':\''+room.no+'\',\'confno\':\''+room.no+'\''
                send(msg)
            }
            break
        case 'allunmute':
            if (room.isVideo) {
                confLog.vconfUnmuteAll(room.name)
                vcs.unMuteAll(room.name, room.number)
            }else {
                method = 'conferencecancemuteall'
                msg = '\'confname\':\''+room.no+'\',\'confno\':\''+room.no+'\''
                send(msg)
            }
            break
        case 'close':
            if (room.isVideo) {
                vcs.closeRoom(room.name, room.number)
                method = 'vconf_close'
                msg = '"confno":"'+room.no+'"'
                send(msg)
                break
            }else{
				typeof cb === 'function' && cb()
			}
            method = 'conferenceclose'
            msg = '\'confname\':\'' + room.no + '\',\'confno\':\'' + room.no +'\''
            send(msg)
            break;
		// 开始录像命令
		case 'startrecord': {
			console.log('开始录像命令 startrecord: name:', room.name, 'number:', room.number)
            if (room.isVideo) {
                vcs.startRecord(room.name, room.number)
                method = 'startRecord'
                msg = '"confno":"'+room.no+'"'
                send(msg)
                break
            }
			break;
		}
		// 结束录像命令
		case 'stoprecord': {
			console.log('结束录像命令 stoprecord: name:', room.name, 'number:', room.number)
            if (room.isVideo) {
                vcs.stopRecord(room.name, room.number)
                method = 'stopRecord'
                msg = '"confno":"'+room.no+'"'
                send(msg)
                break
            }
			break;
		}
        case 'open':
			console.log('room:::::', room)
            if (room.isMeeting) {
				uni.showToast({
					title: '会议已开始',
					icon: 'none'
				})
                return;
            }
            let participants = room.getParticipants()
			console.log('participants::', participants)
            let inviteInfos = []
            let extens = []
            let users = []
            let cameras = []
            if (participants && participants.length > 0) {
                participants.forEach(participant => {
                    let _info = {name:participant.name,number:participant.number, type: participant.type}
                    inviteInfos.push(_info)
                    if (participant.type == 1) {
                        if (registerSIP && caller == participant.number) {
                            return
                        }
                        extens.push(participant.number)
                    }else if (participant.type == 4 || participant.type == 5) {
                        cameras.push(participant.name)
                    } else {
                        if (username != participant.name) {
                            users.push(participant.name)
                        }
                    }
                })
            }

            sendInvite(room.name, inviteInfos)
            if (!room.isVideo) {
                method = 'conferencestart'
                msg = '\'confname\':\'' + room.no + '\',\'confno\':\'' + room.no +'\''
                send(msg)
                return
            }
			console.log('extens::', extens)
            //视频会议
            if (extens.length > 0) {
                method = 'vconf_invite'
                msg = '\'confname\':\'' + room.name + '\',\'displaynum\':\'' + room.number + '\',\'confnum\':\'' + room.number + '\',\'confno\':\'' + room.no
                    + '\',\'extens\':\'' + extens.join().trim() + '\',\'record_switch\':\'' + (room.forceRecord ? '1' : '0') + '\',\'deptId\':\'' + deptId + '\',\'isInvite\':\'0\''
                send(msg)
            }
			console.log('users::', users)
            if (users.length > 0) {
                method = 'vconf_invite_user'
                msg = '\'confname\':\'' + room.name + '\',\'confno\':\'' + room.number
                    + '\',\'users\':\'' + users.join().trim()+'\''
                send(msg)
            }
            //邀请摄像头
			console.log('cameras::', cameras)
            if (cameras.length > 0) {
                cameras.forEach(camera => {
                    inviteCamera(room.name, room.number, camera)
                })
            }
            confLog.vconfStart(room.name)
            if (username) {
                doAction('join')
            }
            setTimeout(() => {
				console.log('room.forceRecord::::', room.forceRecord)
                if (room.forceRecord) {
                    startRecord()
                }
            }, 1000)

            break
        case 'opencamera':
            if (conferenceData.inRoom && room.isVideo) {
                participant = room.getParticipant(username)
                if (participant && participant.rtcPeer) {
                    participant.rtcPeer.peerConnection.getSenders().forEach(sender=>{
                        if (sender.track.kind === 'video') {
                            sender.track.enabled = true
                        }
                    })
                    confLog.vconfUnmuteVideo(room.name, username)
                    vcs.unMuteVideo()
                    participant.muteVideo = false
                    $('.btn-hy button[name="opencamera"]').attr('style','display:none')
                    $('.btn-hy button[name="closecamera"]').attr('style','display:inline-block')
                }
            }
            break
        case 'closecamera':
            if (conferenceData.inRoom && room.isVideo) {
                participant = room.getParticipant(username)
                if (participant && participant.rtcPeer) {
                    participant.rtcPeer.peerConnection.getSenders().forEach(sender=>{
                        if (sender.track.kind === 'video') {
                            sender.track.enabled = false
                        }
                    })
                    confLog.vconfMuteVideo(room.name, username)
                    vcs.muteVideo()
                    participant.muteVideo = true
                    $('.btn-hy button[name="closecamera"]').attr('style','display:none')
                    $('.btn-hy button[name="opencamera"]').attr('style','display:inline-block')
                }
            }
            break
		case 'roomParticipants':
			vcs.roomParticipants(room.name, room.number)
			break;
        default:
            console.log('cannot find name or name not match!,name:{}', name)
    }
}

function inviteCamera(roomName, roomNum, name, send) {
    conferenceApi.queryCameraUrlByName(name).then(response=>{
        if (response.code !== 200) {
            return console.log('get camera play stream address error message:',response.msg)
        }
        let data = response.data
        if (data && data.length > 0) {
            data.forEach(d => {
                if (d.channel) {
                    vcs.joinConference(roomName, roomNum, d.name + '_' + d.channel, 'camera', d.url)
                }else {
                    vcs.joinConference(roomName, roomNum, d.name, 'camera', d.url)
                }
            })
        }else {
            console.log('camera :{} stream url is empty!',name)
            cameraReinvite(roomName,name)
        }
    }).catch(error=>{
        console.error('get camera url error!',err)
        cameraReinvite(roomName,name)
    })
    if (send) {
        let json = {}
        json.name = name
        json.number = name
        json.type = 4
        json.canInvite = false
        let infos = []
        infos.push(json)
        sendInvite(roomName,infos)
    }
}

function cameraReinvite(roomName, name){
    let room = conferenceData.rooms[roomName]
    if (room) {
        room.changeInvite('name', null, name).then(res=>{
            //重新生成邀请
            joinInfo()
        })
    }
}

function sendInvite(name, data) {
    method = 'invite'
    let json = {name:name,data:data}
    msg = '\'data\':' + JSON.stringify(json)
    send(msg)
}

//视频会议邀请处理
function videoConfInvite(data) {
    let inviteUser = data.userID
    let roomName = data.roomName
    let roomNum = data.roomNum
    if (conferenceData.inviteInfo.show) {
        //已有弹屏直接拒绝
        sendRejectVcs(roomName, roomNum)
        return
    }
    let content = '调度员：' + inviteUser + '，邀请您加入视频会议：' + roomName
    conferenceData.inviteInfo.content = content
    conferenceData.inviteInfo.roomName = roomName
    conferenceData.inviteInfo.roomNum = roomNum
    conferenceData.inviteInfo.userId = inviteUser
    conferenceData.inviteInfo.show = true
}
//视频会议拒接处理
function videoConfReject(data) {
    let roomName = data.roomName
    let roomNum = data.roomNum
    let rejectUser = data.rejectUserId
    let room = conferenceData.rooms[roomName]
    if (room) {
        room.changeInvite('name', null, rejectUser).then(response => {
            if (roomName == conferenceData.currentRoom) {
                joinInfo()
            }
        })
    }
}
//会议成员邀请信息同步
function processInviteInfo(data) {
    let infos = data.data
    let roomName = data.name
    let room = conferenceData.rooms[roomName]
    if (room) {
        infos.forEach(info => {
            if (info.name) {
                room.addInviteParticipant(info)
            }
        })
    }
}

function sendRejectVcs(name,number) {
    method = 'reject_vcs'
    let msg = "'confName':'"+name+"','confnum':'"+number+"'"
    send(msg)
}

function createAndShowVmInviteModal(info) {
	console.log('createAndShowVmInviteModal:', info)
	if ($('#vm-invite-modal').length > 0) return;
	const modalHtml = `
		<div id="vm-invite-modal" class="vm-invite-modal">
			<div class="vmi-modal-text">
				<h4>有新的邀请</h4>
				<p class="vmi-text-info">
					<span>邀请人: </span>
					<span class="vmi-text-invite">${info.userID}</span>
					<span>-</span>
					<span>${info.roomName}</span>
				</p>
			</div>
			<div class="vmi-modal-actions">
				<div class="vmi-btn vmi-btn-reject">拒绝</div>
				<div class="vmi-btn vmi-btn-accept">接受</div>
				<span class="vmi-close-btn">&times;</span>
			</div>
		</div>
	`;
	$('body').append(modalHtml);
	
	setTimeout(() => {
		$('#vm-invite-modal').addClass('active');
	}, 10);
	$('#vm-invite-modal .vmi-close-btn').on('click', hideVmInviteModal)
	$('#vm-invite-modal .vmi-btn-reject').on('click', hideVmInviteModal)
	$('#vm-invite-modal .vmi-btn-accept').on('click', async () =>{
		NS_CONFIG.EVENT_BUS.$emit(NS_CONFIG.EVENT_NAMES.nsCallVmOnlyLink, info)
		hideVmInviteModal()
		// NS_CONFIG.EVENT_BUS.$emit('nsCallVm', info)
		// acceptVmInvite(info)
	});
}

function acceptVmInvite(params){
	console.log('acceptVmInvite', params, conferenceData)
	NS_CONFIG.EVENT_BUS.$emit('nsCallVm', params)
	//判断当前是否是会议室
	if (!conferenceData.isHy) {
		//跳转会议室
		conferenceData.currentRoom = conferenceData.inviteInfo.roomName
		conferenceData.isHy = true
		//先获取固定的所有会议室
		conferenceApi.queryConferenceRooms(username).then(result => {
			let data = result.apiResult
			if (data && data.code === 200) {
				let confData = data.data
				console.log('点击会议室菜单，加载会议室左侧树 confData',confData)
				//轮询生成会议室
				generatorConf(confData)
				conferenceData.treeData = confData
				//根据会议室生成树
				loadConferenceLeft()
			}
			//获取视频会议室信息
			vcs.roomInfos()
	
			getconferencelist()
	
			loadRoom(conferenceData.currentRoom)
		})
	}
	setTimeout(() => {
		doAction('join')
		clearInviteInfo()
	}, 500)
	hideVmInviteModal()
}
function hideVmInviteModal() {
	const modal = $('#vm-invite-modal');
	modal.removeClass('active');
	setTimeout(() => modal.remove(), 500);
}

function clearInviteInfo() {
    conferenceData.inviteInfo.show = false
    conferenceData.inviteInfo.userId = ''
    conferenceData.inviteInfo.roomNum = ''
    conferenceData.inviteInfo.roomName = ''
    conferenceData.inviteInfo.content = ''
}

function checkControl() {
    let leftStatus = $('#lstate').html()
    let rightStatus = $('#rstate').html()
    if (leftStatus == '离线' && rightStatus == '离线') {
        $.alert('无控制话机在线！')
        return null
    }
    let controlExten = null
    let _control = $('input[name="phonesel"]:checked').val()
    if (_control == 1) {
        if (leftStatus != '空闲') {
            $.alert('控制话机忙碌！')
            return null
        } else {
            controlExten = caller
        }
    } else {
        if (rightStatus != '空闲') {
            $.alert('控制话机忙碌！')
            return
        } else {
            controlExten = callee
        }
    }
    return controlExten
}

async function checkLines() {
    /*conferenceApi.queryVcsMembers(conferenceConfig.protocol, conferenceConfig.ip, conferenceConfig.port, conferenceConfig.key).then(response=>{
        let count = conferenceConfig.numbers
        if (response.code === 200) {
            count = response.data
        }
        return conferenceConfig.numbers - count
    })*/
    let result = await conferenceApi.queryVcsMembers(conferenceConfig.protocol, conferenceConfig.ip, conferenceConfig.port, conferenceConfig.key)
    let count = conferenceConfig.numbers
    if (result && result.code === 200) {
        count = result.data
    }
    return conferenceConfig.numbers - count
}

function moreConference(confname, extens, isVideo) {
    if (!extens || extens.length <= 0) {
        return
    }
    let msg = ''
    let inviteArr = listData.filter(l => extens.indexOf(l.number) > -1)
    if (isVideo) {
        let options = {
            name: confname,
            number: new Date().getTime(),
            no: confname,
            isVideo: true,
            record: false,
            isTemp: true,
            confApi: conferenceApi
        }
        let room = conferenceUtils.Room(options)
        conferenceData.rooms[confname] = room
        //邀请分机
        confLog.vconfMulti(room.name)
        method = 'vconf_invite'
        msg = '\'confname\':\'' + room.name + '\',\'displaynum\':\'' + conferenceConfig.displayNum+'\',\'confnum\':\''+room.number+'\',\'confno\':\''+room.name+'\',\'type\':\''+'video'
            + '\',\'extens\':\'' + extens.toString().trim() + '\',\'record_switch\':\'0\',\'deptId\':\'' + deptId + '\',\'isInvite\':\'1\''
    }else {
        method = 'mulconference'
        msg = '\'confname\':\'' + confname + '\',\'displaynum\':\'' + conferenceConfig.displayNum + '\',\'isrecord\':\'' + 0 + '\',\'extens\':\'' + extens.toString().trim() + '\''
    }
    if (msg) {
        send(msg)
    }
    //发送邀请信息
    let inviteInfos = []
    inviteArr.forEach(i => {
        let json = {name: i.employeename, number: i.number, type: 1}
        inviteInfos.push(json)
    })
    sendInvite(confname,inviteInfos)

    setTimeout(() => {
        conferenceData.currentRoom = confname
        $('#hy').click()
        if (isVideo) {
            doAction('join')
        }
    }, 500)
}

//切换列表
function changeMode(name,value) {
    selectMeeting(name, value)
    clearSrc(conferenceData.currentRoom)
    if (conferenceData.mode == 'list') {
        removeEventListener()
        loadRoom(conferenceData.currentRoom)
        conferenceData.mode = 'panel'
    } else {
        addEventListener()
        listContent()
        conferenceData.mode = 'list'
    }
}

function clearSrc(roomName) {
    let room = conferenceData.rooms[roomName]
    if (!room || !room.isMeeting || !room.isVideo) {
        return
    }
    let participants = room.getParticipants()
    if (participants && participants.length > 0) {
        participants.forEach(participant=>{
            let node = participant.getElement()
            if (node && participant.rtcPeer) {
                node.pause()
                node.removeAttribute('src')
                node.load()
            }
        })
    }
}

function listContent() {
	console.log('listContentlistContentlistContent')
    let room = conferenceData.rooms[conferenceData.currentRoom]
    if (!room || !room.isMeeting) {
        return
    }
    let participants = room.meetings('Talking')
    //置空主体
    $('#confrenceindex').html('')
    let _html = ''
    //构建主体
    _html += '<div class="list-content">' +
        '<div class="list-left"></div>' +
        '<div class="list-right">' +
        '<div class="list-right-btn"><i class="glyphicon glyphicon-chevron-up" onclick="toTop()"></i></div>' +
        '<div class="list-right-video"></div>' +
        '<div class="list-right-btn"><i class="glyphicon glyphicon-chevron-down" onclick="toBottom()"></i></div>' +
        '</div>' +
        '</div>'
    $('#confrenceindex').html(_html)
    //设置整体的尺寸
    let allHeight = $('#conference').height() - 50
    if (isFull) {
        allHeight = document.body.clientHeight
    }
    $('.list-content').css({'height': allHeight})
    if (participants.length > 0) {
        //生成大页面
        let _main = room.getParticipant(conferenceData.selectParticipant)
        if (!_main) {
            _main = participants[0]
        }
        let _img = ''
        _main.muted ? _img = icon.mute : _img = icon.normal
        let showVideo = (_main.isVcs && !_main.muteVideo)
        let select = _main.type == 1 ? _main.number : _main.name
        let _mainHtml = '<div id="main-va-'+_main.name+'" class="meeting-div h5videowrapper h5container" onclick="selectMeeting(\''+_main.name+'\',\''+select+'\',\''+"main"+'\')" ondblclick="changeMode(\''+_main.name+'\',\''+select+'\')">' +
            '<div id="main-v-' + _main.name + '" style="display: '+(showVideo ? "block":"none")+'" class="meeting-content-div">' +
            '<video id="main-video-' + _main.name + '" class="video-js vjs-default-skin h5video" webkit-playsinline playsinline autoplay></video>' +
            '<div id="main-vn-' + _main.name + '" class="videoname">' +
            '<img src="' + _img + '" id="main-img-'+_main.name+'"/>' + _main.name + ' ' +
            '</div>' +
            '</div>' +
            '<div id="main-a-'+_main.name+'" class="meeting-content-div" style="display: '+(showVideo ? "none":"flex")+'">' +
            '<div class="name-div">' +
            '<div>' +
            '<span title="'+_main.name+'">'+_main.name+'</span>' +
            '</div>' +
            '</div>' +
            '<div id="main-an-' + _main.name + '" class="videoname">' +
            '<img src="' + _img + '" id="main-img-'+_main.name+'"/>' + _main.name + ' ' +
            '</div>' +
            '</div>' +
            '</div>'
        //主体部分插入
        $('.list-left').html(_mainHtml)
        //video标签进行赋值
        let mainNode = document.getElementById('main-video-' + _main.name)
        if (room.isVideo && mainNode) {
            mainNode.srcObject = _main.name == username ? _main.rtcPeer.getLocalStream() : _main.rtcPeer.getRemoteStream()
            if (_main.name == username) {
                mainNode.muted = true
            }
            mainNode.addEventListener('pause',()=>{
                mainNode.play()
            })
        }
        //生成小标签
        let _rightHtml = ''
        participants.forEach(participant=>{
            let _img = ''
            participant.muted ? _img = icon.mute : _img = icon.normal
            let showVideo = (participant.isVcs && !participant.muteVideo)
            let select = participant.type == 1 ? participant.number : participant.name
            let content = '<div id="va-'+participant.name+'" class="meeting-div h5videowrapper h5container" onclick="selectMeeting(\''+participant.name+'\',\''+select+'\')" ondblclick="changeMode(\''+participant.name+'\',\''+select+'\')">' +
                '<div id="v-' + participant.name + '" style="display: '+(showVideo ? "block":"none")+'" class="meeting-content-div">' +
                '<video id="video-' + participant.name + '" class="video-js vjs-default-skin h5video" webkit-playsinline playsinline autoplay></video>' +
                '<audio id="audio-' + participant.name + '" style="display: none" class="video-js vjs-default-skin h5video" webkit-playsinline playsinline autoplay></audio>' +
                '<div id="vn-' + participant.name + '" class="videoname">' +
                '<img src="' + _img + '" id="img-'+participant.name+'"/>' + participant.name + ' ' +
                '</div>' +
                '</div>' +
                '<div id="a-'+participant.name+'" class="meeting-content-div" style="display: '+(showVideo ? "none":"flex")+'">' +
                '<div class="name-div">' +
                '<div>' +
                '<span title="'+participant.name+'">'+participant.name+'</span>' +
                '</div>' +
                '</div>' +
                '<div id="an-' + participant.name + '" class="videoname">' +
                '<img src="' + _img + '" id="img-'+participant.name+'"/>' + participant.name + ' ' +
                '</div>' +
                '</div>' +
                '</div>'
            _rightHtml+=content
        })
        $('.list-right-video').html(_rightHtml)
        //流进行赋值
        if (room.isVideo) {
            //给每个视频窗赋值
            participants.forEach(participant=>{
                if (participant.rtcPeer) {
                    let node = participant.getElement()
                    node.srcObject = participant.name==username ? participant.rtcPeer.getLocalStream() : participant.rtcPeer.getRemoteStream()
                    if (participant.name == username) {
                        node.muted = true
                    }
                    node.addEventListener('pause',()=>{
                        node.play()
                    })
                }
            })
        }
    }
}

function changeMain() {
    let room = conferenceData.rooms[conferenceData.currentRoom]
    if (!room || !room.isMeeting) {
        return
    }
    let _main = room.getParticipant(conferenceData.selectParticipant)
    if (!_main) {
        return
    }
    let _img = ''
    _main.muted ? _img = icon.mute : _img = icon.normal
    let showVideo = (_main.isVcs && !_main.muteVideo)
    let select = _main.type == 1 ? _main.number : _main.name
    let _mainHtml = '<div id="main-va-'+_main.name+'" class="meeting-div h5videowrapper h5container" onclick="selectMeeting(\''+_main.name+'\',\''+select+'\',\''+"main"+'\')" ondblclick="changeMode(\''+_main.name+'\',\''+select+'\')">' +
        '<div id="main-v-' + _main.name + '" style="display: '+(showVideo ? "block":"none")+'" class="meeting-content-div">' +
        '<video id="main-video-' + _main.name + '" class="video-js vjs-default-skin h5video" webkit-playsinline playsinline autoplay></video>' +
        '<div id="main-vn-' + _main.name + '" class="videoname">' +
        '<img src="' + _img + '" id="main-img-'+_main.name+'"/>' + _main.name + ' ' +
        '</div>' +
        '</div>' +
        '<div id="main-a-'+_main.name+'" class="meeting-content-div" style="display: '+(showVideo ? "none":"flex")+'">' +
        '<div class="name-div">' +
        '<div>' +
        '<span title="'+_main.name+'">'+_main.name+'</span>' +
        '</div>' +
        '</div>' +
        '<div id="main-an-' + _main.name + '" class="videoname">' +
        '<img src="' + _img + '" id="main-img-'+_main.name+'"/>' + _main.name + ' ' +
        '</div>' +
        '</div>' +
        '</div>'
    //主体部分插入
    $('.list-left').html(_mainHtml)
    //video标签进行赋值
    let mainNode = document.getElementById('main-video-' + _main.name)
    if (room.isVideo && mainNode) {
        mainNode.srcObject = _main.name == username ? _main.rtcPeer.getLocalStream() : _main.rtcPeer.getRemoteStream()
        if (_main.name == username) {
            mainNode.mute = true
        }
        mainNode.addEventListener('pause',()=>{
            mainNode.play()
        })
    }
}
//给列表添加监听
function addEventListener() {
    let node = document.querySelector('.list-right-video')
    if (node) {
        node.addEventListener('scroll',scrollHandle)
    }
}

function removeEventListener() {
    let node = document.querySelector('.list-right-video')
    if (node) {
        node.removeEventListener('scroll',scrollHandle)
    }
}

function scrollHandle(e) {
    let scrollHeight = e.target.scrollHeight
    let clientHeight = e.target.clientHeight
    topTranslate = e.target.scrollTop
}

function toTop() {
    let node = document.querySelector('.list-right-video')
    if (topTranslate > 0) {
        topTranslate -= getVideoHeight()
    }
    if (topTranslate < 0) {
        topTranslate = 0
    }
    node.scroll(0,topTranslate)
}

function toBottom() {
    let node = document.querySelector('.list-right-video')
    if (topTranslate < (node.scrollHeight - node.clientHeight)) {
        topTranslate += getVideoHeight()
    }
    if (topTranslate > node.scrollHeight) {
        topTranslate = node.scrollHeight
    }
    node.scroll(0,topTranslate)
}

function getVideoHeight() {
    let nodes = document.querySelector('.list-right-video div')
    if (!nodes) {
        return 0
    }
    return nodes.clientHeight
}

//websocket 消息处理
function handleMessage(message) {
    let obj = JSON.parse(message)
    if (!obj) {
        return console.error('recieve message error!,msg:{}', message)
    }
    let roomName = obj.roomName
    let room = null
    if (roomName) {
        room = conferenceData.rooms[roomName]
    }
    let participant = null
	console.log('websocket handleMessage', obj.method)
    switch (obj.method) {
        case 'NoAuth':
            $.alert('视频会议系统对接密钥错误!')
            vcs.dispose()
            break
        case 'ok':
            break
        case 'joinRoom':
            break
        case 'leaveRoom':
            break
        case 'kickRoom':
            break
        case 'startRecord':
            if (room) {
                room.asyncInfo('','startrecord')
                room.record = true
                operationInfo()
            }
            break
        case 'stopRecord':
            if (room) {
                room.record = false
                room.asyncInfo('','stoprecord')
                operationInfo()
            }
            break
        case 'muteVideo':
            if (room) {
                participant = room.getParticipant(obj.name)
                if (participant) {
                    participant.muteVideo = true
                    changeNode(participant)
                    operationInfo()
                }
            }
            break
        case 'unMuteVideo':
            if (room) {
                participant = room.getParticipant(obj.name)
                if (participant) {
                    participant.muteVideo = false
                    changeNode(participant)
                    operationInfo()
                }
            }
            break
        case 'mute':
            if (room) {
                participant = room.getParticipant(obj.name)
                if (participant) {
                    participant.setMute(true)
                    participant.mutedAudio(false,username)
                    changeNode(participant)
                    room.asyncInfo(participant.name, 'mute')
                    operationInfo()
                }
            }
            break
        case 'unMute':
            if (room) {
                participant = room.getParticipant(obj.name)
                if (participant) {
                    participant.setMute(false)
                    participant.mutedAudio(true,username)
                    changeNode(participant)
                    room.asyncInfo(participant.name,'unmute')
                    operationInfo()
                }
            }
            break
        case 'muteAll':
            if (room) {
                room.muteAll()
                participant = room.getParticipant(username)
                if (participant) {
                    participant.mutedAudio(false,username)
                }

                operationInfo()
            }
            break
        case 'unMuteAll':
            if (room) {
                room.unMuteAll()
                participant = room.getParticipant(username)
                if (participant) {
                    participant.mutedAudio(true,username)
                }
                operationInfo()
            }
            break
        case 'BadRequest':
            break
        case 'exist':
            break
        case 'notJoin':
            break
        case 'notMeeting':
            break
        case 'pong':
            break
        case 'existingParticipants':
            console.log('existingParticipantsexistingParticipantsexistingParticipants', room);
			console.log('----------------', obj)
            if (room) {
                if (obj.data && obj.data.length > 0) {
                    //setTreeNum(obj.roomName,obj.data.length)
                    obj.data.forEach(d=>{
                        room.changeVcsParticipant(d).then(response=>{
                            //对生成的成员插入dom
                            let _participants = response.data
                            if (_participants && _participants.length > 0) {
                                _participants.forEach(p=>{
                                    if (conferenceData.currentRoom == room.name) {
                                        if (conferenceData.inRoom) {
                                            insertNode(p)
                                        }else{
                                            loadRoom(room.name)
                                        }
                                    }
                                })
                            }
                        })
                    })
                }
            }
            break
        case 'newParticipantArrived':
            console.log('newParticipantArrivednewParticipantArrivednewParticipantArrived', room);
            if (room) {
                //设置会议室为是否录像
                room.asyncInfo(obj.name, 'enter')
                room.changeVcsParticipant({
                    name: obj.name,
                    type: obj.pType,
                    mute: false,
                    muteVideo: obj.muteVideo
                }).then(response => {
                    //对生成的成员插入dom
                    let _participants = response.data
                    if (_participants && _participants.length > 0) {
                        _participants.forEach(p => {
                            if (conferenceData.currentRoom == room.name) {
                                if (conferenceData.inRoom || p.name == username) {
                                    insertNode(p)
                                } else {
                                    loadRoom(room.name)
                                }
                            }

                        })
                    }
                })
            }
            // changeTreeNum(obj.roomName, 1)
            break
        case 'participantLeft':
            if (room) {
                room.asyncInfo(obj.name,'leave')
                room.vcsLeave({name:obj.name,type:obj.pType}).then(response=>{
                    let _participant = response.data
                    if (_participant) {
                        if (conferenceData.currentRoom == room.name) {
                            if (conferenceData.inRoom) {
                                removeNode(_participant)
                            }else {
                                loadRoom(room.name)
                            }
                        }
                    }
                })
            }
            changeTreeNum(obj.roomName, -1)
            break
        case 'receiveVideoAnswer':
            if (room) {
                room.vcsAnswer(obj)
            }
            break
        case 'iceCandidate':
            if (room) {
                room.vcsCandidate(obj, 0)
            }
            break
        case 'participants':
            console.log('participants participantsparticipants', obj.data);
            if (room) {
                if (obj.data && obj.data.length > 0) {
                    obj.data.forEach(d => {
                        room.changeVcsParticipant(d).then(response=>{
                            //对生成的成员插入dom
                            let _participants = response.data
                            if (_participants && _participants.length > 0) {
                                _participants.forEach(p=>{
                                    insertNode(p)
                                })
                            }
                        })
                    })
                }
				NS_CONFIG.EVENT_BUS.$emit('nsCallGcmGetMembers', obj.data)
            }
            break
        case 'roomInfos':
            if (obj.data) {
                /*message.data.forEach(d=>{
                    //生成会议室,不在固定里的都是临时会议室
                    if (!conferenceData.rooms[d.roomName]) {
                        let _options = {
                            name:d.roomName,
                            number:d.roomNumber,
                            no:d.roomNo,
                            isVideo:true,
                            record:d.record,
                            isTemp:true,
                            confApi:conferenceApi
                        }
                        let newRoom = conferenceUtils.Room(_options)
                        conferenceData.rooms[d.roomName] = newRoom
                    }
                    conferenceData.roomMeetings[d.roomName] = d.participantNames ? d.participantNames.length : 0
                })*/
                //修改会议室的左侧树的数量
                generatorConference(obj.data, true)
            }
            break
        case 'closeRoom':
            if (room) {
                room.dispose().then(response=>{
                    if (room.isTemp) {
                        delete conferenceData.rooms[room.name]
                        delete conferenceData.roomMeetings[room.name]
                        conferenceData.currentRoom = ''
                        loadConferenceLeft()
                    }else{
                        changeTreeNum(room.name,0)
                    }
                    loadRoom(room.isTemp?'':room.name)
					console.log('nsCallCloseAllVm closeRoom:::')
					NS_CONFIG.EVENT_BUS.$emit('nsCallCloseAllVm')
                })
            }
            break
    }
}

function deepCopy(data) {
    var result,oClass = getClass(data)
    if ('object' === oClass) result = {}
    else if (oClass === 'array') result = []
    else return data

    for (const i in data) {
        var copy = data[i]
        if (getClass(copy) === 'object') result[i] = deepCopy(copy)
        else if (getClass(copy) === 'array') result[i] = deepCopy(copy)
        else result[i] = copy
    }
    return result

}

function getClass(o) {
    return Object.prototype.toString.call(o).slice(8, -1)
}

function uuid(len, radix) {
    let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
    let uuid = [], i
    radix = radix || chars.length
    if (len) {
        for (i = 0; i < len; i++) {
            uuid[i] = chars[0 | Math.random() * radix]
        }
    } else {
        let r
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
        uuid[14] = '4'
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]
            }
        }
    }
    return uuid.join('')
}
